package com.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.card.CpuCard;
import com.dao.CardDAO;
import com.dao.UserInfoDAO;
import com.pojo.Card;
import com.pojo.UserInfo;
import com.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CpuCardService {

    @Autowired
    private UserInfoDAO userInfoDAO ;

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate rt ;

    @Value("${upload.dir}")
    private String upload ;

    /**
     * 获取开卡会员信息
     * @param uid
     * @return
     */
    public UserInfo getById(String uid){
        return userInfoDAO.selectById(uid) ;
    }

    /**
     * 开卡
     * @param cid   卡片序列号
     * @param uid   用户id
     * @param ast   复位信息
     * @return
     */
    public Map createCard(String cid , String uid , String ast , String random, String operId){
        Map user = new HashMap() ;
        // 校验卡片是否已经有人使用
        List<Card> c = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , cid)) ;
        UserInfo staff = getById(uid) ;
        if(c.size() != 0) {
            return new HashMap(){{
                put("error","卡已绑定会员");
            }} ;
        }
        //出生日期为0000/00/00则不允许开卡
        String date = staff.getCstime();
        if (date.startsWith("00")) {
            user.put("error","会员出生日期无效，无法开卡");
            return user;
        }
        if (ValidateHelper.isEmptyString(staff.getName())) {
            user.put("error","会员姓名为空，无法开卡");
            return user;
        }
        if (!staff.getBh().matches("^[A-Z]{2}\\d[\\S\\s]*?")){
            user.put("error","编号有问题，无法完成开卡，请重新生成");
            return user;
        }
        String zhukong = null ;
        String xiaofei = null ;

        // 84FA01003880FF400E315041592E5359532E4444463031FFFF006040FFFF0000034B78727F93B59D844B78727F93B59D840001006000808001C73580CA
        // 84FA01003880FF400E315041592E5359532E4444463031FFFF006040FFFF0000037004D7DB6E48014A0F6FBCB2223B608F000100600080800170C85810

        // 获取会员信息
        Card card = new Card() ;
        card.setStatus(1);
        card.setXuliehao(cid);
        card.setStaffId(uid);
        zhukong = UUID.fastUUID().toString().replaceAll("-" , "") ;
        xiaofei = UUID.fastUUID().toString().replaceAll("-" , "") ;
        card.setMiyao(zhukong);
        card.setPin1(xiaofei);
        card.setLuRuCreateTime(new Date());
        card.setSxTime(staff.getDqtime());
        user.put("card" , card) ;
        user.put("pin" , xiaofei) ;
        user.put("uid" , uid) ;
        // 将数据存入redis
//        rt.boundValueOps(cid).set(JSONObject.toJSONString(user));

//        zhukong = "D68D3E245B234180855230775811F9E4" ;
        System.out.println(zhukong);
        // 生成开卡指令
        Map<String , Object> map = new HashMap<String , Object>() ;

        // 生成删除目录结构的指令
        String clearCard = CpuCard.clearCard(zhukong , ast) ;
        String kaika = CpuCard.createCardFirst(ast , zhukong , random) ;
        // 创建目录指令
        String createDir = CpuCard.createDir(zhukong , "1001" , null) ;

        String root = CpuCard.mainDirMiyao(zhukong , null) ;
        String dir = CpuCard.dataDirMiyao(null , null) ;
        String xf = CpuCard.xiaofeiMiyao(null , null) ;
        String qc = CpuCard.quancunMiyao(null , xiaofei) ;
        String tac = CpuCard.tacMiyao(null , null) ;
        String pin = CpuCard.pinMiyao(null , null) ;

        String iconPath = upload+staff.getPicture() ;
        String icon = "" ;
        String img = null ;
        String douhao = HexUtil.encodeHexStr(",".getBytes()) ;  // 分割符
        String end = HexUtil.encodeHexStr("\n".getBytes()) ;    // 结束符
        try{
            img = IconUtil.icon(ImageUtil.rotaImage(iconPath) , 0.9f , 1024*5) ;
            byte[] arr = img.getBytes() ;
            icon = HexUtil.encodeHexStr(arr) ;
        }catch(Exception e) {
            return new HashMap(){{
                put("error","会员头像有问题，不能开卡");
            }} ;
        }
        //icon+douhao +
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
        // 头像 + 姓名 + 编号 + 企业 + 性别 + 到期时间 + 入职时间 + 开卡时间
        String data = HexUtil.encodeHexStr("10000".getBytes()) ;
        // +douhao +HexUtil.encodeHexStr(staff.getName().getBytes())+ douhao + HexUtil.encodeHexStr(staff.getBh().getBytes())+douhao + HexUtil.encodeHexStr(staff.getQiye().getQyname())+douhao+HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes()))+douhao+HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(staff.getRztime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+end
        if(staff.getName() != null) {
            String name = staff.getName().replaceAll("\\n" , "") ;
            name = name.replaceAll("," , "") ;
            data = data + HexUtil.encodeHexStr(name.getBytes()) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getBh() != null) {
            String bh = StringUtils.deleteWhitespace(staff.getBh());
            bh = bh.replaceAll("," , "") ;
            data = data + douhao + HexUtil.encodeHexStr(bh.getBytes()) ;
        }else{
            data = data + douhao ;
        }

        data = data + douhao ;

        if(staff.getSex() != null) {
            data = data + douhao + HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes())) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getDqtime() != null) {
            data = data + douhao + HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes()) ;
        }else{
            data = data + douhao ;
        }

        data = data + douhao ;

        data = data + douhao + HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+douhao+icon + end ;
//        System.out.println(data);
        List<String> res = CpuCard.writeFile("1E" , data) ;

        List<String> files = new ArrayList<String>() ;
        files.add("80E0001E0A2818100040FF001E0000") ;
        files.add("80E000180A2E00F600FFFF17180000") ;
        files.add("80E000020A2D004900002001020018") ;

        map.put("clear_card" , clearCard) ;
        map.put("select_file" , "00A4000002001E") ;
        map.put("kaika" , kaika) ;
        map.put("create_dir" , createDir) ;
        map.put("root" , root) ;
        map.put("dir" , dir) ;
        map.put("xf" , xf) ;
        map.put("qc" , qc) ;
        map.put("tac" , tac) ;
        map.put("pin" , pin) ;
        map.put("createFiles" , files) ;
        map.put("write_file" , res) ;

        card.setOperUser(operId);
        cardDAO.insert(card) ;
        UserInfo staff1 = userInfoDAO.selectById(uid) ;
        staff1.setPin(xiaofei);
        staff1.setCardNo(cid);
        staff1.setBh(StringUtils.deleteWhitespace(staff.getBh()));
        userInfoDAO.updateById(staff1) ;
        return map ;
    }

    /**
     * 新卡开卡
     * @param cid   卡片序列号
     * @param uid   用户id
     * @param ast   复位信息
     * @return
     */
    public Map createNewCard(String cid , String uid , String ast , String random, String operId){
        Map user = new HashMap() ;
        // 校验卡片是否已经有人使用
        List<Card> c = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , cid)) ;
        UserInfo staff = getById(uid) ;
//        List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , staff.getCardNo())) ;
        if(c.size() != 0) {
            return new HashMap(){{
                put("error","卡已绑定员工");
            }} ;
        }
//        if(cards.size() != 0) {
//            return null ;
//        }
        //出生日期为0000/00/00则不允许开卡
        String date = staff.getCstime();
        if (date.startsWith("00")) {
            user.put("error","员工出生日期无效，无法开卡");
            return user;
        }
        if (ValidateHelper.isEmptyString(staff.getName())) {
            user.put("error","员工姓名为空，无法开卡");
            return user;
        }
        if (!staff.getBh().matches("^[A-Z]{2}\\d[\\S\\s]*?")){
            user.put("error","编号有问题，无法完成开卡，请重新生成");
            return user;
        }
        String zhukong = null ;
        String xiaofei = null ;

        // 84FA01003880FF400E315041592E5359532E4444463031FFFF006040FFFF0000034B78727F93B59D844B78727F93B59D840001006000808001C73580CA
        // 84FA01003880FF400E315041592E5359532E4444463031FFFF006040FFFF0000037004D7DB6E48014A0F6FBCB2223B608F000100600080800170C85810

        // 获取员工信息
        Card card = new Card() ;
        card.setStatus(1);
        card.setXuliehao(cid);
        card.setStaffId(uid);
        zhukong = UUID.fastUUID().toString().replaceAll("-" , "") ;
        xiaofei = UUID.fastUUID().toString().replaceAll("-" , "") ;
        card.setMiyao(zhukong);
        card.setPin1(xiaofei);
        card.setLuRuCreateTime(new Date());
        card.setSxTime(staff.getDqtime());
        user.put("card" , card) ;
        user.put("pin" , xiaofei) ;
        user.put("uid" , uid) ;
        // 将数据存入redis
//        rt.boundValueOps(cid).set(JSONObject.toJSONString(user));

//        zhukong = "D68D3E245B234180855230775811F9E4" ;
        System.out.println(zhukong);
        // 生成开卡指令
        Map<String , Object> map = new HashMap<String , Object>() ;


        map.put("qb" , "80D4010015F9F0F0AA33" + zhukong) ;
        map.put("root" , "80D4010015F6F0F0FF33" + zhukong) ;
        map.put("dir_qb" , "80D4010015F9F0F0AA33" + CpuCard.DEFAULT_KEY) ;
        map.put("dir" , "80D4010015F6F0F0FF33" + CpuCard.DEFAULT_KEY) ;
        map.put("pin" , "80D401000DFAF0EF0133" + CpuCard.DEFAULT_PIN) ;
        map.put("xf" , "80D4010115FEF0F00100" + CpuCard.DEFAULT_XIAOFEI_KEY) ;
        map.put("qc" , "80D4010115FFF0F00100" + xiaofei) ;
        map.put("tac" , "80D4010015F4F0F00000" + CpuCard.DEFAULT_KEY) ;
        map.put("file" , "80E0001E07281800F0AAFFFF") ;
        map.put("select_file" , "00A4000002001E") ;


        String iconPath = upload+staff.getPicture() ;
        String icon = "" ;
        String img = null ;
        String douhao = HexUtil.encodeHexStr(",".getBytes()) ;  // 分割符
        String end = HexUtil.encodeHexStr("\n".getBytes()) ;    // 结束符
        try{
            img = IconUtil.icon(ImageUtil.rotaImage(iconPath) , 0.9f , 1024*5) ;
            byte[] arr = img.getBytes() ;
            icon = HexUtil.encodeHexStr(arr) ;
        }catch(Exception e) {
            return new HashMap(){{
                put("error","员工头像有问题，不能开卡");
            }} ;
        }
        //icon+douhao +
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
        // 头像 + 姓名 + 编号 + 企业 + 性别 + 到期时间 + 入职时间 + 开卡时间
        String data = HexUtil.encodeHexStr("10000".getBytes()) ;
        // +douhao +HexUtil.encodeHexStr(staff.getName().getBytes())+ douhao + HexUtil.encodeHexStr(staff.getBh().getBytes())+douhao + HexUtil.encodeHexStr(staff.getQiye().getQyname())+douhao+HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes()))+douhao+HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(staff.getRztime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+end
        if(staff.getName() != null) {
            String name = staff.getName().replaceAll("\\n" , "") ;
            name = name.replaceAll("," , "") ;
            data = data + HexUtil.encodeHexStr(name.getBytes()) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getBh() != null) {
            String bh = StringUtils.deleteWhitespace(staff.getBh());
            bh = bh.replaceAll("," , "") ;
            data = data + douhao + HexUtil.encodeHexStr(bh.getBytes()) ;
        }else{
            data = data + douhao ;
        }

        data = data + douhao ;

        if(staff.getSex() != null) {
            data = data + douhao + HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes())) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getDqtime() != null) {
            data = data + douhao + HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes()) ;
        }else{
            data = data + douhao ;
        }

        data = data + douhao ;

        data = data + douhao + HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+douhao+icon + end ;
//        System.out.println(data);
        List<String> res = CpuCard.writeFile("1E" , data) ;

        List<String> files = new ArrayList<String>() ;

        map.put("write_file" , res) ;

        card.setOperUser(operId);
        cardDAO.insert(card) ;
        UserInfo staff1 = userInfoDAO.selectById(uid) ;
        staff1.setPin(xiaofei);
        staff1.setCardNo(cid);
        staff1.setZkFlag(1);
        staff1.setZkTime(new Date());
        staff1.setBh(StringUtils.deleteWhitespace(staff.getBh()));
        userInfoDAO.updateById(staff1) ;

//        System.out.println(map);
        return map ;
    }

    /**
     * 损坏卡写卡
     * @param cid
     * @param uid
     * @param random
     * @return
     */
    public Map writeFaildCard(String cid , String uid , String ast , String random){
        Map user = new HashMap() ;
        // 校验卡片是否已经有人使用
        UserInfo staff = getById(uid) ;
        List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao", cid));
        if(cards.size() == 0) {
            return new HashMap(){{
                put("error" , "卡不存在") ;
            }} ;
        }
        Card card = cards.get(0) ;
        //出生日期为0000/00/00则不允许开卡
        String date = staff.getCstime();
        if (date.startsWith("00")) {
            user.put("error","会员出生日期无效，无法开卡");
            return user;
        }
        if(StringUtil.isNull(staff.getPin())) {
            staff.setPin(UUID.fastUUID().toString().replaceAll("-" , ""));
        }
        String zhukong = card.getMiyao() ;
        String xiaofei = staff.getPin() ;

        String bh2 = StringUtils.deleteWhitespace(staff.getBh());
        staff.setCardNo(cid);
        staff.setBh(bh2);
        // 将数据存入redis
//        rt.boundValueOps(cid).set(JSONObject.toJSONString(user));
        userInfoDAO.updateById(staff) ;


//        zhukong = "D68D3E245B234180855230775811F9E4" ;
        System.out.println(zhukong);
        // 生成开卡指令
        Map<String , Object> map = new HashMap<String , Object>() ;

        // 生成删除目录结构的指令
        String clearCard = CpuCard.clearCard(zhukong , ast) ;
        String kaika = CpuCard.createCardFirst(ast , zhukong , random) ;
        // 创建目录指令
        String createDir = CpuCard.createDir(zhukong , "1001" , null) ;

        String root = CpuCard.mainDirMiyao(zhukong , null) ;
        String dir = CpuCard.dataDirMiyao(null , null) ;
        String xf = CpuCard.xiaofeiMiyao(null , null) ;
        String qc = CpuCard.quancunMiyao(null , xiaofei) ;
        String tac = CpuCard.tacMiyao(null , null) ;
        String pin = CpuCard.pinMiyao(null , null) ;

        String iconPath = upload+staff.getPicture() ;
        String icon = "" ;
        String img = null ;
        String douhao = HexUtil.encodeHexStr(",".getBytes()) ;  // 分割符
        String end = HexUtil.encodeHexStr("\n".getBytes()) ;    // 结束符
        try{
            img = IconUtil.icon(ImageUtil.rotaImage(iconPath) , 0.9f , 1024*5) ;
            byte[] arr = img.getBytes() ;
            icon = HexUtil.encodeHexStr(arr) ;
        }catch(Exception e) {
            e.printStackTrace();
            return new HashMap(){{
                put("error" , "图片异常") ;
            }} ;
        }
        //icon+douhao +
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
        // 头像 + 姓名 + 编号 + 企业 + 性别 + 到期时间 + 入职时间 + 开卡时间
        String data = HexUtil.encodeHexStr("10000".getBytes()) ;
        // +douhao +HexUtil.encodeHexStr(staff.getName().getBytes())+ douhao + HexUtil.encodeHexStr(staff.getBh().getBytes())+douhao + HexUtil.encodeHexStr(staff.getQiye().getQyname())+douhao+HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes()))+douhao+HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(staff.getRztime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+end
        if(staff.getName() != null) {
            String name = staff.getName().replaceAll("\\n" , "") ;
            name = name.replaceAll("," , "") ;
//            String name = staff.getName() ;
            data = data + HexUtil.encodeHexStr(name.getBytes()) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getBh() != null) {
            String bh = StringUtils.deleteWhitespace(staff.getBh());
            bh = bh.replaceAll("," , "") ;
            data = data + douhao + HexUtil.encodeHexStr(bh.getBytes()) ;
        }else{
            data = data + douhao ;
        }
        data = data + douhao ;

        if(staff.getSex() != null) {
            data = data + douhao + HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes())) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getDqtime() != null) {
            data = data + douhao + HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes()) ;
        }else{
            data = data + douhao ;
        }
        data = data + douhao ;

        data = data + douhao + HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+douhao+icon + end ;
//        System.out.println(data);
        List<String> res = CpuCard.writeFile("1E" , data) ;

        List<String> files = new ArrayList<String>() ;
        files.add("80E0001E0A2818100040FF001E0000") ;
        files.add("80E000180A2E00F600FFFF17180000") ;
        files.add("80E000020A2D004900002001020018") ;

        map.put("clear_card" , clearCard) ;
        map.put("select_file" , "00A4000002001E") ;
        map.put("kaika" , kaika) ;
        map.put("create_dir" , createDir) ;
        map.put("root" , root) ;
        map.put("dir" , dir) ;
        map.put("xf" , xf) ;
        map.put("qc" , qc) ;
        map.put("tac" , tac) ;
        map.put("pin" , pin) ;
        map.put("createFiles" , files) ;
        map.put("write_file" , res) ;

        return map ;
    }


    /**
     * 新卡损坏卡写卡
     * @param cid
     * @param uid
     * @param random
     * @return
     */
    public Map writeFaildNewCard(String cid , String uid , String ast , String random){
        Map user = new HashMap() ;
        // 校验卡片是否已经有人使用
        UserInfo staff = getById(uid) ;
        System.out.println(cid);
        System.out.println(staff.getCardNo());
        /*Card c = cardDAO.selectOne(new QueryWrapper<Card>().eq("xuliehao" , cid)) ;
        if(c == null) {
            return new HashMap(){{
                put("error" , "卡不存在") ;
            }} ;
        }*/
        List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao", cid));
        if(cards.size() == 0) {
            return new HashMap(){{
                put("error" , "卡不存在") ;
            }} ;
        }
        Card card = cards.get(0) ;
        //出生日期为0000/00/00则不允许开卡
        String date = staff.getCstime();
        if (date.startsWith("00")) {
            user.put("error","会员出生日期无效，无法开卡");
            return user;
        }
        if(StringUtil.isNull(staff.getPin())) {
            staff.setPin(UUID.fastUUID().toString().replaceAll("-" , ""));
        }
        String zhukong = card.getMiyao() ;
        String xiaofei = staff.getPin() ;

        String bh2 = StringUtils.deleteWhitespace(staff.getBh());
        staff.setCardNo(cid);
        staff.setBh(bh2);
        // 将数据存入redis
//        rt.boundValueOps(cid).set(JSONObject.toJSONString(user));
        userInfoDAO.updateById(staff) ;

//        zhukong = "D68D3E245B234180855230775811F9E4" ;
        System.out.println(zhukong);
        // 生成开卡指令
        Map<String , Object> map = new HashMap<String , Object>() ;


        String iconPath = upload+staff.getPicture() ;
        String icon = "" ;
        String img = null ;
        String douhao = HexUtil.encodeHexStr(",".getBytes()) ;  // 分割符
        String end = HexUtil.encodeHexStr("\n".getBytes()) ;    // 结束符
        try{
            img = IconUtil.icon(ImageUtil.rotaImage(iconPath) , 0.9f , 1024*5) ;
            byte[] arr = img.getBytes() ;
            icon = HexUtil.encodeHexStr(arr) ;
        }catch(Exception e) {
            e.printStackTrace();
            return new HashMap(){{
                put("error" , "图片异常") ;
            }} ;
        }
        //icon+douhao +
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
        // 头像 + 姓名 + 编号 + 企业 + 性别 + 到期时间 + 入职时间 + 开卡时间
        String data = HexUtil.encodeHexStr("10000".getBytes()) ;
        // +douhao +HexUtil.encodeHexStr(staff.getName().getBytes())+ douhao + HexUtil.encodeHexStr(staff.getBh().getBytes())+douhao + HexUtil.encodeHexStr(staff.getQiye().getQyname())+douhao+HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes()))+douhao+HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(staff.getRztime()).getBytes())+douhao+HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+end
        if(staff.getName() != null) {
            String name = staff.getName().replaceAll("\\n" , "") ;
            name = name.replaceAll("," , "") ;
//            String name = staff.getName() ;
            data = data + HexUtil.encodeHexStr(name.getBytes()) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getBh() != null) {
            String bh = StringUtils.deleteWhitespace(staff.getBh());
            bh = bh.replaceAll("," , "") ;
            data = data + douhao + HexUtil.encodeHexStr(bh.getBytes()) ;
        }else{
            data = data + douhao ;
        }

        data = data + douhao ;

        if(staff.getSex() != null) {
            data = data + douhao + HexUtil.encodeHexStr((staff.getSex() == 0 ? "女".getBytes() : "男".getBytes())) ;
        }else{
            data = data + douhao ;
        }

        if(staff.getDqtime() != null) {
            data = data + douhao + HexUtil.encodeHexStr(sdf.format(staff.getDqtime()).getBytes()) ;
        }else{
            data = data + douhao ;
        }

        data = data + douhao ;

        data = data + douhao + HexUtil.encodeHexStr(sdf.format(new Date()).getBytes())+douhao+icon + end ;
//        System.out.println(data);
        List<String> res = CpuCard.writeFile("1E" , data) ;

        map.put("qb" , "80D4010015F9F0F0AA33" + zhukong) ;
        map.put("root" , "80D4010015F6F0F0FF33" + zhukong) ;
        map.put("dir_qb" , "80D4010015F9F0F0AA33" + CpuCard.DEFAULT_KEY) ;
        map.put("dir" , "80D4010015F6F0F0FF33" + CpuCard.DEFAULT_KEY) ;
        map.put("pin" , "80D401000DFAF0EF0133" + CpuCard.DEFAULT_PIN) ;
        map.put("xf" , "80D4010115FEF0F00100" + CpuCard.DEFAULT_XIAOFEI_KEY) ;
        map.put("qc" , "80D4010115FFF0F00100" + xiaofei) ;
        map.put("tac" , "80D4010015F4F0F00000" + CpuCard.DEFAULT_KEY) ;
        map.put("file" , "80E0001E07281800F0AAFFFF") ;
        map.put("select_file" , "00A4000002001E") ;
        map.put("write_file" , res) ;

        return map ;
    }

    /**
     * 将卡信息写入数据库
     * @param cid
     * @return
     */
    public String insert(String cid){
        return null ;
    }

    /**
     * 充值预处理指令
     * @param money
     * @return
     */
    public Map chongzhiPrepare(String cid , Integer money){
        Map res = new HashMap() ;
        List<Card> card = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , cid)) ;
        if(card.size() == 0) {
            res.put("msg" , "卡片不存在") ;
            return res ;
        }else{
            Card c = card.get(0) ;
            if(c.getStatus() == 2) {
                res.put("msg" , "卡已停用") ;
                return res ;
            }else if(c.getStatus() == 3) {
                res.put("msg" , "卡已挂失") ;
                return res ;
            }else if(c.getStatus() == 4) {
                res.put("msg" , "卡已报废") ;
                return res ;
            }
        }
        res.put("select_file" , "00A40000023F00") ;
        res.put("select_dir" , "00A40000021001") ;
        res.put("pin" , "0020000003123456") ; // 校验pin
        String mon = Hex.encode(money , 8) ;
        res.put("insert" , "805000020B01"+mon+CpuCard.CLIENTID) ;

        return res ;
    }

    /**
     * 充值接口
     * @param info
     * @param money
     * @param uid
     * @return
     */
    public Map chongzhi(String info , Integer money , String uid){
        UserInfo staff = userInfoDAO.selectById(uid) ;
        if(staff == null) {
            return null ;
        }
        Map map = new HashMap() ;
//        String res = CpuCard.chongzhi(info , staff.getPin() , Hex.encode(money , 8)) ;
//        map.put("chongzhi" , res) ;
        map.put("chongzhi","");
        return map ;
    }

    /**
     * 充值接口
     * @param info
     * @param money
     * @param uid
     * @return
     */
    public String chongzhiBalance(String info , Integer money , String uid){
        UserInfo staff = userInfoDAO.selectById(uid) ;
        if(staff == null) {
            return "未找到会员" ;
        }
        BigDecimal price = new BigDecimal(money).divide(new BigDecimal("100")).setScale(0);
        staff.setCardBalance(staff.getCardBalance().add(price));
        if (userInfoDAO.updateById(staff) == 1){
            return null;
        }
        return "充值失败";
    }

    /**
     * 根据卡号查询用户信息
     * @param cid
     * @return
     */
    public UserInfo userinfoByCard(String cid){
        List<Card> xuliehao = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao", cid));
        if(xuliehao.size() == 0) {
            return null ;
        }
        UserInfo staff = userInfoDAO.selectById(xuliehao.get(0).getStaffId()) ;
        return staff ;
    }

    /**
     * 外部认证
     * @param cid
     * @param random
     * @param type
     * @return
     */
    public String waiburenzheng(String cid , String random , Integer type){
        String res = null ;
        if(type == 0){
            res = CpuCard.certification(random , "00000000000000000000000000000000") ;
//            res = CpuCard.certification(random , "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF") ;
        }else if(type == 1) {
            List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao", cid));
            if(cards.size() == 0) {
                Object o = rt.boundValueOps(cid).get();
                if(o != null) {
                    cards.add(JSONObject.parseObject(o.toString()).getObject("card" , Card.class)) ;
                }
            }
            if(cards.size() != 1) {
                return null ;
            }
            String miyao = cards.get(0).getMiyao() ;
            System.out.println("外部认证:"+cards.get(0).getMiyao());
//            miyao = "5b7dd81fa85d4e44b1ff15c1edfd4a87" ;
            res = CpuCard.certification(random , miyao) ;
        }else if(type == 2) {
            res = CpuCard.certification(random , null) ;
        }else if(type == 3) {
            res = CpuCard.certification(random , "C9EEDBDACAD0323032312D31312D3039") ;
        }else if(type == 4) {
            res = CpuCard.certification(random , CpuCard.DEFAULT_DCCK) ;
        }
        return res ;
    }

    /**
     * 充值测试
     * @return
     */
    public Map chongzhiTest(String cid , String info){
        List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , cid)) ;
        if(cards.size() == 0) {
            return new HashMap(){{
                put("error" , "卡不存在") ;
            }} ;
        }
        Card card = cards.get(0) ;
        UserInfo staff = userInfoDAO.selectById(card.getStaffId()) ;
        if(staff == null) {
            return new HashMap(){{
                put("error" , "用户不存在") ;
            }} ;
        }
        String res = CpuCard.chongzhi(info , staff.getPin() , Hex.encode(1 , 8)) ;
        return new HashMap(){{
            put("res" , res) ;
        }} ;
    }

    /**
     * 消费测试
     * @return
     */
    public Map xiaofeiTest(String cid , String info){
        List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , cid)) ;
        if(cards.size() == 0) {
            return new HashMap(){{
                put("error" , "卡不存在") ;
            }} ;
        }
        Card card = cards.get(0) ;
        UserInfo staff = userInfoDAO.selectById(card.getStaffId()) ;
        if(staff == null) {
            return new HashMap(){{
                put("error" , "用户不存在") ;
            }} ;
        }
        String res = CpuCard.xiaofei(info , null , Hex.encode(1 , 8)) ;
        return new HashMap(){{
            put("res" , res) ;
        }} ;
    }
}